<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="用户名">
          <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="action-container">
      <el-button type="primary" @click="handleAdd">新增管理员</el-button>
      <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="adminList"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="用户名" prop="username" min-width="120" />
      <el-table-column label="头像" width="80" align="center">
        <template #default="{ row }">
          <el-avatar :size="40" :src="row.avatar || defaultAvatar" />
        </template>
      </el-table-column>
      <el-table-column label="昵称" prop="nickname" min-width="120" />
      <el-table-column label="角色" width="120" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.roleType === 'super_admin'" type="danger">超级管理员</el-tag>
          <el-tag v-else-if="row.roleType === 'admin'" type="warning">普通管理员</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="登录时间" prop="loginTime" width="160" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="(val) => handleStatusChange(row, val)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" align="center">
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" @click="handleResetPwd(row)">重置密码</el-button>
          <el-button type="text" style="color: #f56c6c" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑管理员对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      destroy-on-close
      append-to-body
    >
      <el-form
        ref="adminFormRef"
        :model="adminForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="adminForm.username" placeholder="请输入用户名" :disabled="dialog.type === 'edit'" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="adminForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="adminForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="adminForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item v-if="dialog.type === 'add'" label="密码" prop="password">
          <el-input v-model="adminForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="roleType">
          <el-select v-model="adminForm.roleType" placeholder="请选择角色" style="width: 100%">
            <el-option label="超级管理员" value="super_admin" />
            <el-option label="普通管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleAvatarChange"
          >
            <img v-if="avatarUrl" :src="avatarUrl" class="avatar-image" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="adminForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="adminForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPwdDialog.visible"
      title="重置密码"
      width="500px"
      destroy-on-close
    >
      <div class="reset-pwd-info">
        <p>您正在重置管理员 <b>{{ resetPwdDialog.username }}</b> 的密码</p>
      </div>
      <el-form
        ref="resetPwdFormRef"
        :model="resetPwdForm"
        :rules="resetPwdRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input v-model="resetPwdForm.password" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPwdForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetPwdDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitResetPwd">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getAdminList, getAdminDetail, addAdmin, updateAdmin, deleteAdmin, updateAdminStatus, resetAdminPassword } from '@/api/user'

const loading = ref(false)
const adminList = ref([])
const total = ref(0)
const selectedIds = ref([])
const adminFormRef = ref()
const resetPwdFormRef = ref()
const avatarUrl = ref('')
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  username: '',
  status: undefined
})

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  roleType: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 重置密码校验规则
const resetPwdRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetPwdForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 对话框状态
const dialog = reactive({
  visible: false,
  title: '',
  type: ''
})

// 重置密码对话框状态
const resetPwdDialog = reactive({
  visible: false,
  userId: '',
  username: ''
})

// 管理员表单对象
const adminForm = reactive({
  id: undefined,
  username: '',
  nickname: '',
  phone: '',
  email: '',
  password: '',
  roleType: 'admin',
  avatar: '',
  status: 1,
  remark: ''
})

// 重置密码表单
const resetPwdForm = reactive({
  userId: '',
  password: '',
  confirmPassword: ''
})

// 获取管理员列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getAdminList(queryParams)
    adminList.value = res.data.rows
    total.value = res.data.total
  } catch (error) {
    console.error('获取管理员列表失败', error)
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  getList()
})

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.username = ''
  queryParams.status = undefined
  handleQuery()
}

// 表格选择行变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 每页数量变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

// 页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getList()
}

// 状态变化
const handleStatusChange = async (row, status) => {
  try {
    await updateAdminStatus(row.id, { status })
    ElMessage.success(`${status === 1 ? '启用' : '禁用'}成功`)
  } catch (error) {
    row.status = status === 1 ? 0 : 1
    console.error('修改状态失败', error)
  }
}

// 添加管理员
const handleAdd = () => {
  resetAdminForm()
  dialog.title = '添加管理员'
  dialog.type = 'add'
  dialog.visible = true
}

// 编辑管理员
const handleEdit = async (row) => {
  resetAdminForm()
  dialog.title = '编辑管理员'
  dialog.type = 'edit'
  dialog.visible = true
  
  try {
    const res = await getAdminDetail(row.id)
    Object.assign(adminForm, res.data)
    avatarUrl.value = adminForm.avatar
  } catch (error) {
    console.error('获取管理员详情失败', error)
  }
}

// 删除管理员
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除管理员 "${row.username}" 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteAdmin(row.id)
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}

// 批量删除管理员
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 个管理员吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await Promise.all(selectedIds.value.map(id => deleteAdmin(id)))
    ElMessage.success('批量删除成功')
    getList()
  }).catch(() => {})
}

// 重置密码
const handleResetPwd = (row) => {
  resetPwdForm.userId = row.id
  resetPwdForm.password = ''
  resetPwdForm.confirmPassword = ''
  resetPwdDialog.userId = row.id
  resetPwdDialog.username = row.username
  resetPwdDialog.visible = true
}

// 提交重置密码
const submitResetPwd = () => {
  resetPwdFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      await resetAdminPassword(resetPwdForm.userId, { password: resetPwdForm.password })
      ElMessage.success('密码重置成功')
      resetPwdDialog.visible = false
    } catch (error) {
      console.error('重置密码失败', error)
    }
  })
}

// 重置管理员表单
const resetAdminForm = () => {
  adminForm.id = undefined
  adminForm.username = ''
  adminForm.nickname = ''
  adminForm.phone = ''
  adminForm.email = ''
  adminForm.password = ''
  adminForm.roleType = 'admin'
  adminForm.avatar = ''
  adminForm.status = 1
  adminForm.remark = ''
  avatarUrl.value = ''
}

// 处理头像上传
const handleAvatarChange = (file) => {
  // 实际应用中需要调用上传API
  // 这里模拟上传成功后的行为
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarUrl.value = e.target.result
    adminForm.avatar = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

// 提交表单
const submitForm = () => {
  adminFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      if (dialog.type === 'add') {
        await addAdmin(adminForm)
        ElMessage.success('添加成功')
      } else {
        await updateAdmin(adminForm.id, adminForm)
        ElMessage.success('修改成功')
      }
      
      dialog.visible = false
      getList()
    } catch (error) {
      console.error('保存失败', error)
    }
  })
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .filter-container {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
  }
  
  .action-container {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  
  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      
      &:hover {
        border-color: var(--el-color-primary);
      }
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 120px;
      height: 120px;
      text-align: center;
      line-height: 120px;
    }
    
    .avatar-image {
      width: 120px;
      height: 120px;
      display: block;
      border-radius: 50%;
      object-fit: cover;
    }
  }
  
  .reset-pwd-info {
    font-size: 14px;
    color: #606266;
    margin-bottom: 20px;
    
    b {
      color: #409eff;
    }
  }
}
</style> 